package com.nifostasky.comic.service.impl;

import com.alibaba.fastjson.JSON;
import com.nifostasky.comic.common.utils.JsonUtil;
import com.nifostasky.comic.common.utils.ShellUtil;
import com.nifostasky.comic.entitys.CoDetailedInfo;
import com.nifostasky.comic.entitys.CoSpiderInfo;
import com.nifostasky.comic.exceptions.BusinessException;
import com.nifostasky.comic.service.CoSpiderInfoService;
import com.nifostasky.comic.service.ShellService;
import com.nifostasky.comic.vos.ChapterInfoComicVO;
import com.nifostasky.comic.vos.KeywordSearchVO;
import com.nifostasky.comic.vos.PictureInfoComicVO;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ShellServiceImpl implements ShellService {
    @Value("${shell.path.rootWindowsPath}")
    private String rootWindowsPath;
    @Value("${shell.path.rootLinuxPath}")
    private String rootLinuxPath;
    @Value("${shell.encoded.shellJava}")
    private String shellJava;
    @Value("${shell.encoded.javaShell}")
    private String javaShell;

    @Autowired
    private CoSpiderInfoService coSpiderInfoService;

    @Override
    public List<CoDetailedInfo> searchMainPageComic(Long pyId) {
        String commands = "python -u -c \"import sys ; import io ; import %s as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.indexComic())\"";
        String result = this.getShellResult(pyId,commands);
        List<CoDetailedInfo> resultObject = JsonUtil.handleJsonArray(result, CoDetailedInfo.class);
        return resultObject;
    }

    @Override
    public KeywordSearchVO searchComic(Integer pageIndex, String keyword, Long pyId) {
        String commands = "python -u -c \"import sys ; import io ; import %s as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.keywordSearch('"
                + keyword +"',"
                + pageIndex +"))\"";
        if (Objects.isNull(pageIndex) || Objects.isNull(keyword) || Objects.isNull(pyId))
            throw new BusinessException("传递参数不全",-500);
        String result = this.getShellResult(pyId,commands);
        KeywordSearchVO resultObject = JsonUtil.handleJsonObject(result, KeywordSearchVO.class);
        return resultObject;
    }

    @Override
    public ChapterInfoComicVO detailComic(Integer pageIndex, String url, Long pyId) {
        String commands = "python -u -c \"import sys ; import io ; import %s as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.chapterInfoComic('"
                + url +"',"+ pageIndex + "))\"";
        if (Objects.isNull(url) || Objects.isNull(pyId))
            throw new BusinessException("传递参数不全",-500);
        String result = this.getShellResult(pyId,commands);
        ChapterInfoComicVO resultObject = JsonUtil.handleJsonObject(result, ChapterInfoComicVO.class);
        return resultObject;
    }

    @Override
    public PictureInfoComicVO pictureComic(String url, Long pyId) {
        String commands = "python -u -c \"import sys ; import io ; import %s as comic; sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ; print(comic.pictureInfoComic('"
                + url +"'))\"";
        if (Objects.isNull(url) || Objects.isNull(pyId))
            throw new BusinessException("传递参数不全",-500);
        String result = this.getShellResult(pyId,commands);
        PictureInfoComicVO resultObject = JsonUtil.handleJsonObject(result, PictureInfoComicVO.class);
        return resultObject;
    }

    /**
     * 获取shell执行结果
     * @param pyId
     * @param commands
     * @return
     */
    @SneakyThrows
    private String getShellResult(Long pyId, String commands){
//        String sysEncode = System.getProperty("file.encoding");
        CoSpiderInfo spiderInfo = coSpiderInfoService.getById(pyId);
        commands = String.format(commands,spiderInfo.getPyName().split("\\.")[0]);
//        String encoding = JsonUtil.getEncoding(commands);
//        commands = new String(commands.getBytes(encoding),javaShell);
        List<String> shells = new ArrayList<>();
        if (ShellUtil.getOs()) {
            shells.add("cmd");
            shells.add(rootWindowsPath.split(":")[0] + ":");
            shells.add("cd " + rootWindowsPath + spiderInfo.getPyPath());
        }else {
            shells.add("cd "+ rootLinuxPath + spiderInfo.getPyPath());
        }
        shells.add(commands);
        //这里执行py程序,指定编码 java -> shell 为javaShell编码
        String result = ShellUtil.pyInteractive(shells,javaShell,shellJava);
//        if (Objects.nonNull(result)) {
//            String encodingResult = JsonUtil.getEncoding(result);
//            result = new String(result.getBytes(encodingResult), shellJava);
//        }
        return result;
    }


}
